package com.okhttpstudy;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.okhttpstudy.okhttp.OkHttpClientManager;
import com.okhttpstudy.okhttp.ResultCallback;
import com.okhttpstudy.utils.LogUti;
import com.okhttpstudy.utils.MD5Utils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private OkHttpClient client;
    String tag = MainActivity.this.getClass().getSimpleName();
    private TextView tv_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button bt_get = (Button) findViewById(R.id.btn_get);
        Button bt_post = (Button) findViewById(R.id.btn_post);
        tv_content = (TextView) findViewById(R.id.tv_content);
        bt_get.setOnClickListener(this);
        bt_post.setOnClickListener(this);
        client = new OkHttpClient();

    }

    private void asyGet(String url) throws IOException {
        final Request request = new Request.Builder()
                .get()
                .tag(this)
                .url(url)
                .build();//Request是OkHttp中访问的请求，Builder是辅助类，Response即OkHttp中的响应
        final Response response = client.newCall(request).execute();


        Call call = client.newCall(request);


        /**
         * 我们希望以异步的方式去执行请求，所以我们调用的是call.enqueue，将call加入调度队列，然后等待任务执行完成，我们在Callback中即可得到结果。
         */
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                try {
                    throw new IOException("UnException code" + response);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }

            /**
             *
             * @param call
             * @param response
             * @throws IOException
             * onResponse回调的参数是response，一般情况下，比如
             * 我们希望获得返回的字符串，可以通过response.body().string()获取；
             * 如果希望获得返回的二进制字节数组，则调用response.body().bytes()；
             * 如果你想拿到返回的inputStream，则调用response.body().byteStream()
             */
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("info", "打印GET响应的数据：:" + response.body().string());
            }
        });

    }

    private void asyPost(String url) throws IOException {
        RequestBody formBody = new FormBody.Builder()
                .add("u_Phone", "18659815391")//传入参数？
                .add("code", "111111")//传入参数？
                .add("encodestr", MD5Utils.ecodeTwice("18659815391" + "111111" + "action_login"))//传入参数？
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("info", String.valueOf(e));

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.i("info", "打印POST响应的数据：" + response.body().string());
            }
        });

    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_get) {
            initAsyGet();
        } else {
            initAsyPost();
        }
    }

    private void initAsyPost() {

        Map<String, String> map = new HashMap<>();
     /*   map.put("u_Phone", "18659815391");
        map.put("url", "http://app.all-wifi.cn/Service.php?a=checkMobile");
        map.put("code", "111111");
        map.put("encodestr", MD5Utils.ecodeTwice("18659815391" + "111111" + "action_login"));*/
        map.put("sname","david");
        OkHttpClientManager.getInstance().postAsyn(this, "http://15h0l63133.iask.in/CodeIgniter-3.0.2/index.php/MyService/getData", map, new ResultCallback() {
            @Override
            public void onError(String msg) {
                LogUti.i("info", "post onError" + msg);
            }

            @Override
            public void onResponse(final String result) {
//                Toast.makeText(MainActivity.this, "result" + result, Toast.LENGTH_LONG).show();
                tv_content.setText(result.toString());
                LogUti.i("info", "post onResponse result:" + result.toString());
            }
        });

    }

    private void initAsyGet() {
        Map<String, String> map = new HashMap<>();
        map.put("params1", "aaaa");
        map.put("params2", "bbbb");
        OkHttpClientManager.getInstance().getAsyn(MainActivity.this, "http://hwzhang.top", map, new ResultCallback() {
            @Override
            public void onError(String msg) {
                LogUti.i("info", "get onError" + msg);

            }

            @Override
            public void onResponse(String result) {
                LogUti.i("info", "get onResponse result:" + result.toString());
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkHttpClientManager.getInstance().cancelCallsWithTag(tag);
    }
}
